package com.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.utils.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.annotation.IgnoreAuth;

import com.entity.ErshoushangpinEntity;
import com.entity.view.ErshoushangpinView;

import com.service.ErshoushangpinService;
import com.service.TokenService;
import com.utils.PageUtils;
import com.utils.R;
import com.utils.MD5Util;
import com.utils.MPUtil;
import com.utils.CommonUtil;
import java.io.IOException;
import com.service.StoreupService;
import com.entity.StoreupEntity;

// 新增导入
import java.util.stream.Collectors;
import com.service.YonghuService;
import com.service.OrdersService;
import com.entity.YonghuEntity;
import com.entity.OrdersEntity;
import com.baomidou.mybatisplus.plugins.Page;
import java.util.Collections;
import java.util.Comparator;

/**
 * 二手书籍
 * 后端接口
 * @author 
 * @email 
 * @date 2025-09-13 08:43:58
 */
@RestController
@RequestMapping("/ershoushangpin")
public class ErshoushangpinController {
    @Autowired
    private ErshoushangpinService ershoushangpinService;

    @Autowired
    private StoreupService storeupService;

    // 新增用户和订单服务
    @Autowired
    private YonghuService yonghuService;
    
    @Autowired
    private OrdersService ordersService;

    


    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,ErshoushangpinEntity ershoushangpin,
		HttpServletRequest request){
		String tableName = request.getSession().getAttribute("tableName").toString();
		if(tableName.equals("chiwuzhe")) {
			ershoushangpin.setChiwuzhanghao((String)request.getSession().getAttribute("username"));
		}
        EntityWrapper<ErshoushangpinEntity> ew = new EntityWrapper<ErshoushangpinEntity>();

		PageUtils page = ershoushangpinService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, ershoushangpin), params), params));

        return R.ok().put("data", page);
    }
    
    /**
     * 前端列表 - 支持智能推荐
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,ErshoushangpinEntity ershoushangpin, 
		HttpServletRequest request){
        
        // 检查是否为首页推荐请求（通过limit=4判断首页调用）
        String limitStr = (String) params.get("limit");
        boolean isHomePageRequest = "4".equals(limitStr);
        
        if (isHomePageRequest) {
            System.out.println("检测到首页调用，返回智能推荐结果");
            
            // 获取当前用户ID
            Long currentUserId = null;
            Object userIdObj = request.getSession().getAttribute("userId");
            if (userIdObj != null) {
                currentUserId = Long.valueOf(userIdObj.toString());
                System.out.println("当前用户ID: " + currentUserId);
            }
            
            int limit = 4;
            List<ErshoushangpinEntity> recommendedBooks = null;
            
            if (currentUserId != null) {
                // 尝试协同过滤推荐
                recommendedBooks = collaborativeFilteringRecommend(currentUserId, limit);
                System.out.println("协同过滤推荐结果数量: " + (recommendedBooks != null ? recommendedBooks.size() : 0));
            }
            
            // 如果推荐结果不足，用热门书籍补充
            if (recommendedBooks == null || recommendedBooks.size() < limit) {
                int needCount = limit - (recommendedBooks != null ? recommendedBooks.size() : 0);
                System.out.println("需要补充热门书籍数量: " + needCount);
                
                List<Long> excludeIds = new ArrayList<>();
                if (recommendedBooks != null) {
                    excludeIds = recommendedBooks.stream().map(ErshoushangpinEntity::getId).collect(Collectors.toList());
                }
                List<ErshoushangpinEntity> popularBooks = getPopularBooks(needCount, excludeIds);
                
                if (recommendedBooks == null) {
                    recommendedBooks = popularBooks;
                } else {
                    recommendedBooks.addAll(popularBooks);
                }
            }
            
            // 构造分页结果格式
            PageUtils pageResult = new PageUtils(recommendedBooks, recommendedBooks.size(), 1, limit);
            return R.ok().put("data", pageResult);
        }
        
        // 普通列表查询逻辑
        EntityWrapper<ErshoushangpinEntity> ew = new EntityWrapper<ErshoushangpinEntity>();
		PageUtils page = ershoushangpinService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, ershoushangpin), params), params));
        return R.ok().put("data", page);
    }

	/**
     * 列表
     */
    @RequestMapping("/lists")
    public R list( ErshoushangpinEntity ershoushangpin){
       	EntityWrapper<ErshoushangpinEntity> ew = new EntityWrapper<ErshoushangpinEntity>();
      	ew.allEq(MPUtil.allEQMapPre( ershoushangpin, "ershoushangpin")); 
        return R.ok().put("data", ershoushangpinService.selectListView(ew));
    }

	 /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(ErshoushangpinEntity ershoushangpin){
        EntityWrapper< ErshoushangpinEntity> ew = new EntityWrapper< ErshoushangpinEntity>();
 		ew.allEq(MPUtil.allEQMapPre( ershoushangpin, "ershoushangpin")); 
		ErshoushangpinView ershoushangpinView =  ershoushangpinService.selectView(ew);
		return R.ok("查询二手书籍成功").put("data", ershoushangpinView);
    }
	
    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        ErshoushangpinEntity ershoushangpin = ershoushangpinService.selectById(id);
		ershoushangpin.setClicknum(ershoushangpin.getClicknum()+1);
		ershoushangpin.setClicktime(new Date());
		ershoushangpinService.updateById(ershoushangpin);
        return R.ok().put("data", ershoushangpin);
    }

    /**
     * 前端详情
     */
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id){
        ErshoushangpinEntity ershoushangpin = ershoushangpinService.selectById(id);
		ershoushangpin.setClicknum(ershoushangpin.getClicknum()+1);
		ershoushangpin.setClicktime(new Date());
		ershoushangpinService.updateById(ershoushangpin);
        return R.ok().put("data", ershoushangpin);
    }
    


    /**
     * 赞或踩
     */
    @RequestMapping("/thumbsup/{id}")
    public R vote(@PathVariable("id") String id,String type){
        ErshoushangpinEntity ershoushangpin = ershoushangpinService.selectById(id);
        if(type.equals("1")) {
        	ershoushangpin.setThumbsupnum(ershoushangpin.getThumbsupnum()+1);
        } else {
        	ershoushangpin.setCrazilynum(ershoushangpin.getCrazilynum()+1);
        }
        ershoushangpinService.updateById(ershoushangpin);
        return R.ok("投票成功");
    }

    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody ErshoushangpinEntity ershoushangpin, HttpServletRequest request){
    	ershoushangpin.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
    	//ValidatorUtils.validateEntity(ershoushangpin);
    	ershoushangpin.setAddtime(new Date());
        ershoushangpinService.insert(ershoushangpin);
        return R.ok();
    }
    
    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody ErshoushangpinEntity ershoushangpin, HttpServletRequest request){
    	ershoushangpin.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
    	//ValidatorUtils.validateEntity(ershoushangpin);
    	ershoushangpin.setAddtime(new Date());
        ershoushangpinService.insert(ershoushangpin);
        return R.ok();
    }



    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody ErshoushangpinEntity ershoushangpin, HttpServletRequest request){
        //ValidatorUtils.validateEntity(ershoushangpin);
        ershoushangpinService.updateById(ershoushangpin);//全部更新
        return R.ok();
    }


    

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        ershoushangpinService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
    
    /**
     * 提醒接口
     */
	@RequestMapping("/remind/{columnName}/{type}")
	public R remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request, 
						 @PathVariable("type") String type,@RequestParam Map<String, Object> map) {
		map.put("column", columnName);
		map.put("type", type);
		
		if(type.equals("2")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			Date remindStartDate = null;
			Date remindEndDate = null;
			if(map.get("remindstart")!=null) {
				Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
				c.setTime(new Date()); 
				c.add(Calendar.DAY_OF_MONTH,remindStart);
				remindStartDate = c.getTime();
				map.put("remindstart", sdf.format(remindStartDate));
			}
			if(map.get("remindend")!=null) {
				Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
				c.setTime(new Date());
				c.add(Calendar.DAY_OF_MONTH,remindEnd);
				remindEndDate = c.getTime();
				map.put("remindend", sdf.format(remindEndDate));
			}
		}
		
		Wrapper<ErshoushangpinEntity> wrapper = new EntityWrapper<ErshoushangpinEntity>();
		if(map.get("remindstart")!=null) {
			wrapper.ge(columnName, map.get("remindstart"));
		}
		if(map.get("remindend")!=null) {
			wrapper.le(columnName, map.get("remindend"));
		}

		String tableName = request.getSession().getAttribute("tableName").toString();
		if(tableName.equals("chiwuzhe")) {
			wrapper.eq("chiwuzhanghao", (String)request.getSession().getAttribute("username"));
		}

		int count = ershoushangpinService.selectCount(wrapper);
		return R.ok().put("count", count);
	}
	
	/**
     * 前端智能排序 - 集成推荐算法
     */
	@IgnoreAuth
    @RequestMapping("/autoSort")
    public R autoSort(@RequestParam Map<String, Object> params,ErshoushangpinEntity ershoushangpin, HttpServletRequest request,String pre){
        System.out.println("=== 开始执行前端智能排序 (autoSort) ===");
        
        try {
            // 获取当前用户ID
            Long currentUserId = null;
            System.out.println("Session信息:");
            if (request.getSession() != null) {
                System.out.println("  Session ID: " + request.getSession().getId());
                System.out.println("  Session attributes:");
                java.util.Enumeration<String> attributeNames = request.getSession().getAttributeNames();
                while (attributeNames.hasMoreElements()) {
                    String attrName = attributeNames.nextElement();
                    Object attrValue = request.getSession().getAttribute(attrName);
                    System.out.println("    " + attrName + " = " + attrValue);
                }
                
                if (request.getSession().getAttribute("userId") != null) {
                    currentUserId = Long.valueOf(request.getSession().getAttribute("userId").toString());
                    System.out.println("从session获取到用户ID: " + currentUserId);
                } else {
                    System.out.println("Session中没有userId，尝试其他方式获取用户ID");
                    // 尝试从其他session属性获取用户ID
                    Object user = request.getSession().getAttribute("user");
                    if (user != null) {
                        System.out.println("找到user对象: " + user);
                    }
                }
            } else {
                System.out.println("Session为空");
            }
            
            // 为了测试，如果没有获取到用户ID，暂时使用用户222的ID
            if (currentUserId == null) {
                System.out.println("未获取到用户ID，为了测试使用用户222的ID: 1679101034337");
                currentUserId = 1679101034337L;
            }
            
            // 获取分页参数
            int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
            int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 10;
            System.out.println("分页参数 - page: " + page + ", limit: " + limit);
            
            List<ErshoushangpinEntity> recommendedBooks = null;
            
            if (currentUserId != null) {
                // 执行协同过滤推荐
                recommendedBooks = collaborativeFilteringRecommend(currentUserId, limit);
                System.out.println("协同过滤推荐结果数量: " + (recommendedBooks != null ? recommendedBooks.size() : 0));
                
                // 添加协同过滤推荐结果的详细信息
                if (recommendedBooks != null && !recommendedBooks.isEmpty()) {
                    System.out.println("=== 协同过滤推荐详细信息 ===");
                    for (int i = 0; i < recommendedBooks.size(); i++) {
                        ErshoushangpinEntity book = recommendedBooks.get(i);
                        System.out.println("  协同过滤推荐第" + (i+1) + "本: ID=" + book.getId() + ", 名称=" + book.getShangpinmingcheng());
                    }
                    System.out.println("=== 协同过滤推荐详细信息结束 ===");
                }
            }
            
            // 如果推荐结果不足，用热门书籍补充
            if (recommendedBooks == null || recommendedBooks.size() < limit) {
                int needCount = limit - (recommendedBooks != null ? recommendedBooks.size() : 0);
                System.out.println("需要补充热门书籍数量: " + needCount);
                
                List<Long> excludeIds2 = new ArrayList<>();
                if (recommendedBooks != null) {
                    excludeIds2 = recommendedBooks.stream().map(ErshoushangpinEntity::getId).collect(Collectors.toList());
                }
                List<ErshoushangpinEntity> popularBooks = getPopularBooks(needCount, excludeIds2);
                
                // 添加热门书籍的详细信息
                if (popularBooks != null && !popularBooks.isEmpty()) {
                    System.out.println("=== 热门书籍补充详细信息 ===");
                    for (int i = 0; i < popularBooks.size(); i++) {
                        ErshoushangpinEntity book = popularBooks.get(i);
                        System.out.println("  热门书籍第" + (i+1) + "本: ID=" + book.getId() + ", 名称=" + book.getShangpinmingcheng() + 
                                         ", 点击数=" + book.getClicknum() + ", 点赞数=" + book.getThumbsupnum());
                    }
                    System.out.println("=== 热门书籍补充详细信息结束 ===");
                }
                
                if (recommendedBooks == null) {
                    recommendedBooks = popularBooks;
                    System.out.println("协同过滤无结果，使用纯热门书籍推荐");
                } else {
                    System.out.println("合并协同过滤推荐(" + recommendedBooks.size() + "本)和热门书籍(" + (popularBooks != null ? popularBooks.size() : 0) + "本)");
                    recommendedBooks.addAll(popularBooks);
                }
                
                System.out.println("最终推荐结果数量: " + recommendedBooks.size());
                
                // 添加详细的调试信息 - 输出最终推荐结果的详细信息
                System.out.println("=== 最终推荐结果详细信息 ===");
                for (int i = 0; i < recommendedBooks.size(); i++) {
                    ErshoushangpinEntity book = recommendedBooks.get(i);
                    System.out.println("  第" + (i+1) + "本: ID=" + book.getId() + ", 名称=" + book.getShangpinmingcheng() + 
                                     ", 点击数=" + book.getClicknum() + ", 点赞数=" + book.getThumbsupnum());
                }
                System.out.println("=== 最终推荐结果详细信息结束 ===");
            }
            
            // 如果仍然没有结果，使用原始逻辑
            if (recommendedBooks == null || recommendedBooks.isEmpty()) {
                System.out.println("推荐算法无结果，使用原始排序逻辑");
                EntityWrapper<ErshoushangpinEntity> ew = new EntityWrapper<ErshoushangpinEntity>();
                Map<String, Object> newMap = new HashMap<String, Object>();
                Map<String, Object> param = new HashMap<String, Object>();
                Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    String key = entry.getKey();
                    String newKey = entry.getKey();
                    if (pre.endsWith(".")) {
                        newMap.put(pre + newKey, entry.getValue());
                    } else if (StringUtils.isEmpty(pre)) {
                        newMap.put(newKey, entry.getValue());
                    } else {
                        newMap.put(pre + "." + newKey, entry.getValue());
                    }
                }
                params.put("sort", "clicknum");
                params.put("order", "desc");
                PageUtils fallbackResult = ershoushangpinService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, ershoushangpin), params), params));
                return R.ok().put("data", fallbackResult);
            }
            
            // 构造分页结果
            PageUtils pageResult = new PageUtils(recommendedBooks, recommendedBooks.size(), limit, page);
            
            System.out.println("=== 智能排序执行完成 ===");
            return R.ok().put("data", pageResult);
            
        } catch (Exception e) {
            System.err.println("智能排序执行出错: " + e.getMessage());
            e.printStackTrace();
            
            // 出错时使用原始逻辑
            System.out.println("出错回退到原始排序逻辑");
            EntityWrapper<ErshoushangpinEntity> ew = new EntityWrapper<ErshoushangpinEntity>();
            Map<String, Object> newMap = new HashMap<String, Object>();
            Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String key = entry.getKey();
                String newKey = entry.getKey();
                if (pre.endsWith(".")) {
                    newMap.put(pre + newKey, entry.getValue());
                } else if (StringUtils.isEmpty(pre)) {
                    newMap.put(newKey, entry.getValue());
                } else {
                    newMap.put(pre + "." + newKey, entry.getValue());
                }
            }
            newMap.put("sort", "clicknum");
            newMap.put("order", "desc");
            PageUtils fallbackPage = ershoushangpinService.queryPage(newMap, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, ershoushangpin), newMap), newMap));
            return R.ok().put("data", fallbackPage);
        }
    }

    /**
     * 前端智能推荐排序 - 协同过滤版本
     * 基于用户行为的个性化推荐算法
     */
    @IgnoreAuth
    @RequestMapping("/autoSort2")
    public R autoSort2(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        System.out.println("=== 开始执行智能推荐算法 (autoSort2) ===");
        
        try {
            // 获取当前用户ID
            Long currentUserId = null;
            if (request.getSession().getAttribute("userId") != null) {
                currentUserId = Long.valueOf(request.getSession().getAttribute("userId").toString());
                System.out.println("当前用户ID: " + currentUserId);
            } else {
                System.out.println("未登录用户，使用热门推荐");
            }
            
            // 获取分页参数
            int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
            int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 4;
            System.out.println("分页参数 - page: " + page + ", limit: " + limit);
            
            List<ErshoushangpinEntity> recommendedBooks = null;
            
            if (currentUserId != null) {
                // 执行协同过滤推荐
                recommendedBooks = collaborativeFilteringRecommend(currentUserId, limit);
                System.out.println("协同过滤推荐结果数量: " + (recommendedBooks != null ? recommendedBooks.size() : 0));
            }
            
            // 如果推荐结果不足，用热门书籍补充
            if (recommendedBooks == null || recommendedBooks.size() < limit) {
                int needCount = limit - (recommendedBooks != null ? recommendedBooks.size() : 0);
                System.out.println("需要补充热门书籍数量: " + needCount);
                
                List<Long> excludeIds3 = new ArrayList<>();
                if (recommendedBooks != null) {
                    excludeIds3 = recommendedBooks.stream().map(ErshoushangpinEntity::getId).collect(Collectors.toList());
                }
                List<ErshoushangpinEntity> popularBooks = getPopularBooks(needCount, excludeIds3);
                
                if (recommendedBooks == null) {
                    recommendedBooks = popularBooks;
                } else {
                    recommendedBooks.addAll(popularBooks);
                }
                
                System.out.println("最终推荐结果数量: " + recommendedBooks.size());
            }
            
            // 构造分页结果
            PageUtils pageResult = new PageUtils(recommendedBooks, recommendedBooks.size(), limit, page);
            
            System.out.println("=== 智能推荐算法执行完成 ===");
            return R.ok().put("data", pageResult);
            
        } catch (Exception e) {
            System.err.println("智能推荐算法执行出错: " + e.getMessage());
            e.printStackTrace();
            
            // 出错时返回热门书籍
            EntityWrapper<ErshoushangpinEntity> ew = new EntityWrapper<ErshoushangpinEntity>();
            params.put("sort", "clicknum");
            params.put("order", "desc");
            PageUtils page = ershoushangpinService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, new ErshoushangpinEntity()), params), params));
            return R.ok().put("data", page);
        }
    }

    /**
     * 协同过滤推荐接口
     * 基于用户行为的书籍推荐算法
     */
    @IgnoreAuth
    @RequestMapping("/recommend")
    public R recommend(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        System.out.println("=== 开始执行协同过滤推荐算法 ===");
        
        try {
            // 获取当前用户ID
            Long currentUserId = null;
            if (request.getSession().getAttribute("userId") != null) {
                currentUserId = Long.valueOf(request.getSession().getAttribute("userId").toString());
                System.out.println("当前用户ID: " + currentUserId);
            }
            
            // 获取分页参数
            int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
            int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 4;
            System.out.println("分页参数 - page: " + page + ", limit: " + limit);
            
            List<ErshoushangpinEntity> recommendedBooks = null;
            
            if (currentUserId != null) {
                // 执行协同过滤推荐
                recommendedBooks = collaborativeFilteringRecommend(currentUserId, limit);
                System.out.println("协同过滤推荐结果数量: " + recommendedBooks.size());
            }
            
            // 如果推荐结果不足，用热门书籍补充
            if (recommendedBooks == null || recommendedBooks.size() < limit) {
                int needCount = limit - (recommendedBooks != null ? recommendedBooks.size() : 0);
                List<ErshoushangpinEntity> popularBooks = getPopularBooks(needCount, 
                    recommendedBooks != null ? 
                    recommendedBooks.stream().map(ErshoushangpinEntity::getId).collect(Collectors.toList()) : 
                    new ArrayList<>());
                
                if (recommendedBooks == null) {
                    recommendedBooks = popularBooks;
                    System.out.println("使用热门书籍推荐，数量: " + popularBooks.size());
                } else {
                    recommendedBooks.addAll(popularBooks);
                    System.out.println("补充热门书籍，总数量: " + recommendedBooks.size());
                }
            }
            
            // 构造分页结果
            PageUtils pageResult = new PageUtils(recommendedBooks, recommendedBooks.size(), limit, page);
            System.out.println("=== 推荐算法执行完成 ===");
            
            return R.ok().put("data", pageResult);
            
        } catch (Exception e) {
            System.err.println("推荐算法执行出错: " + e.getMessage());
            e.printStackTrace();
            
            // 出错时返回默认的热门推荐
            List<ErshoushangpinEntity> defaultBooks = getPopularBooks(
                params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 4, 
                new ArrayList<>());
            PageUtils pageResult = new PageUtils(defaultBooks, defaultBooks.size(), 
                params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 4, 
                params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1);
            
            return R.ok().put("data", pageResult);
        }
    }
    
    /**
     * 协同过滤推荐算法实现
     */
    private List<ErshoushangpinEntity> collaborativeFilteringRecommend(Long userId, int limit) {
        System.out.println("--- 开始执行协同过滤算法 ---");
        
        // 1. 获取当前用户的行为数据
        Map<Long, Double> currentUserPreferences = getUserPreferences(userId);
        System.out.println("当前用户偏好数量: " + currentUserPreferences.size());
        
        if (currentUserPreferences.isEmpty()) {
            System.out.println("当前用户无历史行为，使用基于分类的推荐");
            return getRecommendationsByCategory(userId, limit);
        }
        
        // 2. 获取所有其他用户的行为数据
        List<YonghuEntity> allUsers = yonghuService.selectList(new EntityWrapper<YonghuEntity>());
        System.out.println("总用户数: " + allUsers.size());
        
        // 3. 计算用户相似度
        Map<Long, Double> userSimilarities = new HashMap<>();
        int validUsers = 0;
        
        for (YonghuEntity user : allUsers) {
            if (!user.getId().equals(userId)) {
                Map<Long, Double> otherUserPreferences = getUserPreferences(user.getId());
                if (!otherUserPreferences.isEmpty()) {
                    validUsers++;
                    double similarity = calculateCosineSimilarity(currentUserPreferences, otherUserPreferences);
                    if (similarity > 0.05) { // 降低相似度阈值以适应数据稀疏性
                        userSimilarities.put(user.getId(), similarity);
                        System.out.println("找到相似用户: " + user.getId() + ", 相似度: " + String.format("%.3f", similarity));
                    }
                }
            }
        }
        
        System.out.println("有行为数据的用户数: " + validUsers + ", 相似用户数量: " + userSimilarities.size());
        
        // 4. 如果相似用户太少，使用混合推荐策略
        if (userSimilarities.size() < 2) {
            System.out.println("相似用户数量不足，使用混合推荐策略");
            return getHybridRecommendations(userId, currentUserPreferences, limit);
        }
        
        // 5. 找出相似用户喜欢但当前用户未接触过的书籍
        Map<Long, Double> bookScores = new HashMap<>();
        for (Map.Entry<Long, Double> entry : userSimilarities.entrySet()) {
            Long similarUserId = entry.getKey();
            Double similarity = entry.getValue();
            
            Map<Long, Double> similarUserPreferences = getUserPreferences(similarUserId);
            for (Map.Entry<Long, Double> bookEntry : similarUserPreferences.entrySet()) {
                Long bookId = bookEntry.getKey();
                Double preference = bookEntry.getValue();
                
                // 如果当前用户没有接触过这本书
                if (!currentUserPreferences.containsKey(bookId)) {
                    double score = similarity * preference;
                    bookScores.put(bookId, bookScores.getOrDefault(bookId, 0.0) + score);
                }
            }
        }
        
        System.out.println("推荐书籍候选数量: " + bookScores.size());
        
        // 6. 按分数排序并获取推荐结果
        List<Long> recommendedBookIds = bookScores.entrySet().stream()
            .sorted(Map.Entry.<Long, Double>comparingByValue().reversed())
            .limit(limit)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
        
        System.out.println("协同过滤推荐书籍ID: " + recommendedBookIds);
        
        // 7. 获取推荐书籍的详细信息
        List<ErshoushangpinEntity> recommendedBooks = new ArrayList<>();
        for (Long bookId : recommendedBookIds) {
            ErshoushangpinEntity book = ershoushangpinService.selectById(bookId);
            if (book != null) {
                recommendedBooks.add(book);
                System.out.println("协同过滤推荐书籍: " + book.getShangpinmingcheng() + " (分数: " + String.format("%.3f", bookScores.get(bookId)) + ")");
            }
        }
        
        System.out.println("--- 协同过滤算法执行完成 ---");
        return recommendedBooks;
    }
    
    /**
     * 获取用户偏好数据
     * 基于用户的收藏、点赞和购买行为计算偏好分数
     */
    private Map<Long, Double> getUserPreferences(Long userId) {
        Map<Long, Double> preferences = new HashMap<>();
        System.out.println("正在获取用户 " + userId + " 的偏好数据...");
        
        try {
            // 1. 从收藏表获取用户行为
            EntityWrapper<StoreupEntity> storeupWrapper = new EntityWrapper<>();
            storeupWrapper.eq("userid", userId);
            storeupWrapper.eq("tablename", "ershoushangpin");
            List<StoreupEntity> storeups = storeupService.selectList(storeupWrapper);
            
            System.out.println("用户 " + userId + " 收藏/点赞数据: " + storeups.size() + " 条");
            for (StoreupEntity storeup : storeups) {
                Long bookId = storeup.getRefid();
                String type = storeup.getType();
                
                double score = 0.0;
                String actionType = "";
                if ("1".equals(type)) { // 收藏
                    score = 3.0;
                    actionType = "收藏";
                } else if ("21".equals(type)) { // 点赞
                    score = 2.0;
                    actionType = "点赞";
                } else if ("22".equals(type)) { // 点踩
                    score = -1.0;
                    actionType = "点踩";
                }
                
                preferences.put(bookId, preferences.getOrDefault(bookId, 0.0) + score);
                System.out.println("  " + actionType + "行为: 书籍ID=" + bookId + ", 权重=" + score);
            }
            
            // 2. 从订单表获取购买行为
            EntityWrapper<OrdersEntity> ordersWrapper = new EntityWrapper<>();
            ordersWrapper.eq("userid", userId);
            ordersWrapper.eq("tablename", "ershoushangpin");
            List<OrdersEntity> orders = ordersService.selectList(ordersWrapper);
            
            System.out.println("用户 " + userId + " 订单数据: " + orders.size() + " 条");
            for (OrdersEntity order : orders) {
                Long bookId = order.getGoodid();
                // 根据订单状态调整权重
                double score = 5.0; // 基础购买权重
                if ("已完成".equals(order.getStatus())) {
                    score = 6.0; // 完成订单权重更高
                } else if ("已支付".equals(order.getStatus()) || "已发货".equals(order.getStatus())) {
                    score = 5.0;
                } else if ("已取消".equals(order.getStatus())) {
                    score = 1.0; // 取消订单权重较低
                }
                
                preferences.put(bookId, preferences.getOrDefault(bookId, 0.0) + score);
                System.out.println("  购买行为: 书籍ID=" + bookId + ", 状态=" + order.getStatus() + ", 权重=" + score);
            }
            
            System.out.println("用户 " + userId + " 总偏好项目数: " + preferences.size());
            preferences.forEach((bookId, totalScore) -> {
                System.out.println("  书籍ID: " + bookId + ", 综合评分: " + String.format("%.1f", totalScore));
            });
            
        } catch (Exception e) {
            System.err.println("获取用户 " + userId + " 偏好数据时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
        
        return preferences;
    }
    
    /**
     * 计算余弦相似度
     */
    private double calculateCosineSimilarity(Map<Long, Double> preferences1, Map<Long, Double> preferences2) {
        // 找出共同的书籍
        java.util.Set<Long> commonBooks = new java.util.HashSet<>(preferences1.keySet());
        commonBooks.retainAll(preferences2.keySet());
        
        if (commonBooks.isEmpty()) {
            return 0.0;
        }
        
        // 计算点积
        double dotProduct = 0.0;
        for (Long bookId : commonBooks) {
            dotProduct += preferences1.get(bookId) * preferences2.get(bookId);
        }
        
        // 计算向量长度
        double norm1 = Math.sqrt(preferences1.values().stream().mapToDouble(v -> v * v).sum());
        double norm2 = Math.sqrt(preferences2.values().stream().mapToDouble(v -> v * v).sum());
        
        if (norm1 == 0.0 || norm2 == 0.0) {
            return 0.0;
        }
        
        return dotProduct / (norm1 * norm2);
    }
    
    /**
     * 基于分类的推荐（用于新用户）
     */
    private List<ErshoushangpinEntity> getRecommendationsByCategory(Long userId, int limit) {
        System.out.println("为新用户执行基于分类的推荐");
        
        // 获取各分类中评分最高的书籍
        List<ErshoushangpinEntity> categoryBooks = new ArrayList<>();
        
        // 获取所有分类
        EntityWrapper<ErshoushangpinEntity> categoryWrapper = new EntityWrapper<>();
        categoryWrapper.setSqlSelect("DISTINCT wupinfenlei");
        List<ErshoushangpinEntity> categories = ershoushangpinService.selectList(categoryWrapper);
        
        // 从每个分类中选择热度最高的书籍
        for (ErshoushangpinEntity category : categories) {
            EntityWrapper<ErshoushangpinEntity> bookWrapper = new EntityWrapper<>();
            bookWrapper.eq("wupinfenlei", category.getWupinfenlei());
            bookWrapper.orderBy("clicknum", false);
            bookWrapper.orderBy("thumbsupnum", false);
            bookWrapper.last("LIMIT 2"); // 每个分类取2本
            
            List<ErshoushangpinEntity> booksInCategory = ershoushangpinService.selectList(bookWrapper);
            categoryBooks.addAll(booksInCategory);
            
            if (categoryBooks.size() >= limit) {
                break;
            }
        }
        
        // 如果还不够，补充热门书籍
        if (categoryBooks.size() < limit) {
            int remainingCount = limit - categoryBooks.size();
            List<Long> excludeIds = categoryBooks.stream().map(ErshoushangpinEntity::getId).collect(Collectors.toList());
            List<ErshoushangpinEntity> additionalBooks = getPopularBooks(remainingCount, excludeIds);
            categoryBooks.addAll(additionalBooks);
        }
        
        // 限制返回数量
        List<ErshoushangpinEntity> result = categoryBooks.stream().limit(limit).collect(Collectors.toList());
        System.out.println("基于分类推荐书籍数量: " + result.size());
        
        return result;
    }
    
    /**
     * 混合推荐策略（协同过滤 + 内容过滤）
     */
    private List<ErshoushangpinEntity> getHybridRecommendations(Long userId, Map<Long, Double> userPreferences, int limit) {
        System.out.println("执行混合推荐策略");
        
        List<ErshoushangpinEntity> hybridResults = new ArrayList<>();
        
        // 1. 基于用户偏好的分类推荐
        Map<String, Double> categoryPreferences = getCategoryPreferences(userPreferences);
        System.out.println("用户分类偏好: " + categoryPreferences);
        
        List<ErshoushangpinEntity> contentBasedBooks = getContentBasedRecommendations(categoryPreferences, userPreferences.keySet(), limit / 2);
        hybridResults.addAll(contentBasedBooks);
        
        // 2. 补充热门书籍
        if (hybridResults.size() < limit) {
            int remainingCount = limit - hybridResults.size();
            List<Long> excludeIds = new ArrayList<>(userPreferences.keySet());
            excludeIds.addAll(hybridResults.stream().map(ErshoushangpinEntity::getId).collect(Collectors.toList()));
            
            List<ErshoushangpinEntity> popularBooks = getPopularBooks(remainingCount, excludeIds);
            hybridResults.addAll(popularBooks);
        }
        
        System.out.println("混合推荐结果数量: " + hybridResults.size());
        return hybridResults.stream().limit(limit).collect(Collectors.toList());
    }
    
    /**
     * 分析用户的分类偏好
     */
    private Map<String, Double> getCategoryPreferences(Map<Long, Double> userPreferences) {
        Map<String, Double> categoryScores = new HashMap<>();
        
        for (Map.Entry<Long, Double> entry : userPreferences.entrySet()) {
            Long bookId = entry.getKey();
            Double score = entry.getValue();
            
            ErshoushangpinEntity book = ershoushangpinService.selectById(bookId);
            if (book != null && book.getWupinfenlei() != null) {
                String category = book.getWupinfenlei();
                categoryScores.put(category, categoryScores.getOrDefault(category, 0.0) + score);
            }
        }
        
        return categoryScores;
    }
    
    /**
     * 基于内容的推荐（根据分类偏好）
     */
    private List<ErshoushangpinEntity> getContentBasedRecommendations(Map<String, Double> categoryPreferences, 
                                                                      java.util.Set<Long> excludeBookIds, int limit) {
        List<ErshoushangpinEntity> recommendations = new ArrayList<>();
        
        // 按分类偏好排序
        List<Map.Entry<String, Double>> sortedCategories = categoryPreferences.entrySet().stream()
            .sorted(Map.Entry.<String, Double>comparingByValue().reversed())
            .collect(Collectors.toList());
        
        int booksPerCategory = Math.max(1, limit / Math.max(sortedCategories.size(), 1));
        
        for (Map.Entry<String, Double> categoryEntry : sortedCategories) {
            String category = categoryEntry.getKey();
            
            EntityWrapper<ErshoushangpinEntity> wrapper = new EntityWrapper<>();
            wrapper.eq("wupinfenlei", category);
            if (!excludeBookIds.isEmpty()) {
                wrapper.notIn("id", excludeBookIds);
            }
            wrapper.orderBy("clicknum", false);
            wrapper.orderBy("thumbsupnum", false);
            wrapper.last("LIMIT " + (booksPerCategory + 1));
            
            List<ErshoushangpinEntity> categoryBooks = ershoushangpinService.selectList(wrapper);
            recommendations.addAll(categoryBooks);
            
            if (recommendations.size() >= limit) {
                break;
            }
        }
        
        return recommendations.stream().limit(limit).collect(Collectors.toList());
    }
    
    /**
     * 获取热门书籍（当推荐数据不足时使用）
     */
    private List<ErshoushangpinEntity> getPopularBooks(int limit, List<Long> excludeIds) {
        System.out.println("获取热门书籍，数量: " + limit + ", 排除ID: " + excludeIds);
        
        EntityWrapper<ErshoushangpinEntity> wrapper = new EntityWrapper<>();
        if (!excludeIds.isEmpty()) {
            wrapper.notIn("id", excludeIds);
        }
        
        // 按点击次数和点赞数排序
        wrapper.orderBy("clicknum", false);
        wrapper.orderBy("thumbsupnum", false);
        
        Page<ErshoushangpinEntity> page = new Page<>(1, limit);
        Page<ErshoushangpinEntity> result = ershoushangpinService.selectPage(page, wrapper);
        
        List<ErshoushangpinEntity> books = result.getRecords();
        System.out.println("热门书籍数量: " + books.size());
        
        return books;
    }

}
